package category

import (
	"github.com/gin-gonic/gin"
	"strconv"

	"com.jiaguyu/dao/db"
	"com.jiaguyu/until"

	"com.jiaguyu/logger"
	"com.jiaguyu/model"
)

//获取分类列表
func GetCategoryListHandle(ctx *gin.Context) {
	//从列表中加载分类数据

	categoryList, err := db.GetCategoryList()

	if err != nil {
		until.ResponseError(ctx, until.ErrCodeServerErr)
		logger.Error("服务器繁忙:err=%V\n", err)
		return
	}
	until.ResponseSuccess(ctx, categoryList)
}

//获取问题列表
func GetQuestionListHandle(ctx *gin.Context) {
	//获取 分类 categoryIdStr
	categoryIdStr, ok := ctx.GetQuery("category_id")
	if !ok {
		until.ResponseError(ctx, until.ErrCodeParameter)
		logger.Error("参数错误:err=%V\n", ok)
		return
	}

	//将id转为int64
	categoryId, err := strconv.ParseInt(categoryIdStr, 10, 64)
	if err != nil {
		logger.Error("参数错误:err=%V,categoryId:%V\n", err, categoryId)
		until.ResponseError(ctx, until.ErrCodeParameter)
		return
	}
	//获取数据所有问题内容
	questionList, err := db.GetQuestionList(categoryId)
	if err != nil {
		logger.Error("获取数据失败")
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}

	if len(questionList) == 0 {
		until.ResponseSuccess(ctx, questionList)
		return
	}

	//批量拿数据
	var userIdList []int64
	userIdMap := make(map[int64]bool, 16)
	for _, question := range questionList {
		_, ok = userIdMap[question.AuthorId]
		if ok {
			continue
		}
		userIdMap[question.AuthorId] = true
		userIdList = append(userIdList, question.AuthorId)
	}
	//获取所有的userInfo数据
	userInfoList, err := db.GetUserInfoList(userIdList)
	if err != nil {
		logger.Error("获取用户信息失败")
		until.ResponseError(ctx, until.ErrCodeServerBusy)
		return
	}
	var categoryQuestionArr []*model.CategoryQuestion

	for _, question := range questionList {
		var categoryQuestion = &model.CategoryQuestion{}
		categoryQuestion.Question = *question
		categoryQuestion.CreateTimeStr = categoryQuestion.CreateTime.Format("2006/1/2 15:04:05")
		for _, userInfo := range userInfoList {
			if userInfo.UserId == question.AuthorId {
				categoryQuestion.AuthorName = userInfo.NickName
				break
			}
		}
		categoryQuestionArr = append(categoryQuestionArr, categoryQuestion)
	}
	until.ResponseSuccess(ctx, categoryQuestionArr)
}
